<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>淘宝搜索案例</title>
  <!-- 导入页面的基本样式 -->
  <link rel="stylesheet" href="./css/search.css" />
</head>

<body>
  <div class="container">
    <!-- Logo -->
    <img src="./images/taobao_logo.png" alt="" class="logo" />

    <div class="box">
      <!-- tab 栏 -->
      <div class="tabs">
        <div class="tab-active">宝贝</div>
        <div>店铺</div>
      </div>
      <!-- 搜索区域（搜索框和搜索按钮） -->
      <div class="search-box">
        <input type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
          搜索
        </button>
      </div>

      <!-- 搜索建议列表 -->
      <div id="suggest-list">
        <div class="suggest-item">搜索建议1</div>
        <div class="suggest-item">搜索建议2</div>
        <div class="suggest-item">搜索建议3</div>
        <div class="suggest-item">搜索建议4</div>
      </div>
    </div>
  </div>

  <!-- 导入 jQuery -->
  <script src="./lib/jquery.js"></script>
  <!-- 导入 axios -->
  <script src="./lib/axios.js"></script>
  <!-- <script>
    $('.ipt').on('input', function () {
      let val = $('.inp').val();
      if (val == '') {
        $('#suggest-list').html('');
        return
      };

      axios.get('http://www.liulongbin.top:3009/api/sug', {
        params:{
          q:val
        }
          
        })
        .then(({
          data: res
        }) =>{
           $('#suggest-list').html('');

           res.result.forEach(item => {
             let one= $(`<div class="suggest-item">${item}</div>`);
               $('#suggest-list').append(one);
             
           });
        })
    })
  </script> -->


  <script>

    let timer = null;

    $(".ipt").on("input", function() {

    // 清除定时器
    clearTimeout(timer);

    // 2.如何给建议？看我们说了啥？要获取我们输入内容是个啥！
    let val = $(".ipt").val();
    if (val == "") {
    $("#suggest-list").html("");
    return
    };


    timer = setTimeout(() => {
    // 3.ajax请求，拿到搜索建议列表
    axios.get("http://www.liulongbin.top:3009/api/sug", {
    params: {
    q: val
    }
    })
    .then(({
    data: res
    }) => {

    // 4，循环遍历
    // 4.1 suggest-list 清空
    // 4.2 循环遍历
    $("#suggest-list").html("");

    res.result.forEach(item => {
    let one = $(`<div class="suggest-item">${item}</div>`);
    $("#suggest-list").append(one);
    });

    });

    }, 500);

    });
  </script>


</body>

</html>